package main

import (
	"os"

	"gitee.com/dark.H/gs"
	"gitee.com/dark.H/gt"
)

var (
	Pwd = gs.Str(".")
)

type Rnager struct {
	Cwd gs.Str
}

func (r *Rnager) Ls(n ...gs.Str) (files gs.List[gs.Str]) {
	if n != nil {
		d := r.Cwd.PathJoin(n[0].Printable(true).Str())
		d.Ls().Every(func(no int, i gs.Str) {
			if i.IsDir() {
				files = files.Add(i.Basename().Color("g"))
			} else {
				files = files.Add(i.Basename())
			}

		})
	} else {
		if r.Cwd.IsDir() {
			r.Cwd.Ls().Every(func(no int, i gs.Str) {
				if i.IsDir() {
					files = files.Add(i.Basename().Color("g"))
				} else {
					files = files.Add(i.Basename())
				}
			})
		}
	}

	return
}

func (r *Rnager) Cd(name gs.Str) *Rnager {
	d := r.Cwd.PathJoin(name.Str())
	if d.IsDir() {
		r.Cwd = d
	}
	return r
}

func main() {
	r := &Rnager{
		Cwd: gs.Str(os.Args[1]),
	}
	files := r.Ls()
	ranger := gt.NewListItemsPanel(files)
	ranger.SetBar(false).SetSizeWidth(40)
	ranger.OnFileLike(func(enterItem gs.Str) {
		gs.Str("enter " + enterItem + "cwd:" + r.Cwd + "\n").ToFile("/tmp/test.log")
		r.Cd(enterItem)
	}, func(oldstate gt.ListState[gs.Str]) {
		r.Cd("..")
	}, func(mainSeleted gs.Str) (subitems gs.List[gs.Str]) {
		gs.Str("ls " + r.Cwd + " item : " + mainSeleted + "\n").ToFile("/tmp/test.log")
		fs := r.Ls(mainSeleted)
		ranger.SetTitle(mainSeleted)
		return fs
	})
	ranger.Focus()
}
